package com.shenbianyun.bosskgpay.utils;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Base64;

import static com.shenbianyun.bosskgpay.utils.PasswordCheckUtils.desDecrypt;

public class DESEncryption {

    public static String encryptPassword(String plainPassword) {
        long floor = System.currentTimeMillis() / 60000;
        String encryptedPassword = desEncrypt(plainPassword, String.valueOf(floor));
        if (encryptedPassword == null) {
            // 处理加密失败，例如记录日志
            System.err.println("加密失败：密钥可能无效");
        }
        return encryptedPassword;
    }

    private static String desEncrypt(String plainText, String key) {
        try {
            byte[] encryptedBytes = DESUtils1.encrypt(
                    plainText.getBytes(StandardCharsets.UTF_8),
                    key
            );
            return Base64.getEncoder().encodeToString(encryptedBytes);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

class DESUtils1 {
    // 保持与提供的解密代码相同的实现
    public static byte[] encrypt(byte plainText[], String desKey) throws Exception {
        SecureRandom sr = new SecureRandom();
        byte[] rawKeyData = desKey.getBytes(StandardCharsets.UTF_8);
        DESKeySpec dks = new DESKeySpec(rawKeyData);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey key = keyFactory.generateSecret(dks);
        Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key, sr);
        return cipher.doFinal(plainText);
    }

    public static void main(String[] args) {
        String plain = "111111";
        String encrypted = DESEncryption.encryptPassword(plain);
        System.out.println("加密结果: " + encrypted);

        String decrypted = desDecrypt(encrypted);
        System.out.println("解密结果: " + decrypted);
    }



}
